<template>
    <div class="dialog">
        <el-dialog
            title="视频上传"
            :visible.sync="videoFormVisible"
            :before-close="handleClose"
            width="700px"
        >
            <el-divider></el-divider>
            <el-form
                :model="formData"
                :rules="rules"
                ref="uploadVideo"
                label-width="100px"
                label-position="right"
                size="small"
                style="width: 100%"
            >
                <el-form-item label="视频标题" prop="videoTitle">
                    <el-input v-model="formData.videoTitle" placeholder="请输入标题名称"></el-input>
                </el-form-item>

                <!--el-form-item label="视频分类" prop="videoClassId">
                    <el-select
                        v-model="formData.videoClassId"
                        placeholder="请选择"
                        @change="handleChange"
                    >
                        <el-option
                        v-for="item in videoClass"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                        >
                        </el-option>
                    </el-select>
                </el-form-item-->
                <el-form-item label="到期时间" prop="expiration_time">
                    <el-date-picker
                        v-model="formData.expiration_time"
                        type="datetime"
                        :picker-options="pickerOptions"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        default-time="23:59:59"
                        @focus="handleFocus"
                        placeholder="选择到期时间">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="视频文件" prop="videoUrl">
                    <uploadBtn @uploadSuccess="uploadSuccess($event)" v-bind:carTypeId="carTypeId" v-bind:is_done="is_done" v-if="!disabled"></uploadBtn>
                    <div v-else>{{formData.videoUrl}}</div>
                </el-form-item>

                <el-form-item label="视频封面" prop="imageUrl">
                    <div class="header-img">
                        <el-upload
                            action="#"
                            :class="{ 'local-hide': headerHideUpload }"
							:http-request="handleUploadImg"
                            :file-list="imageList"
                            accept=".jpg, .png"
                            list-type="picture-card"
                            :multiple="false"
                            :limit="1"
                            :on-change="selectFile"
                            :on-remove="removeFile"
                        >
                            <i slot="default" class="el-icon-plus"></i>
                        </el-upload>
                        <div class="el-upload__tip">
			    	        <p style="line-height:200%">1. 建议图片像素326*440、652*880（px）
				            <br>2. 图片格式 jpg, png
				            <br>3. 图片大小不超过2M</p>
		                </div>
                    </div>
                </el-form-item>

                <el-form-item position="right">
                    <el-button type="primary" @click="submitForm('uploadVideo')" class="btnSave">提交</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>
<script>
import { brandModel } from "../api"
import uploadBtn from "./video-upload-btn.vue"
import { dateFormatter } from "@/common/js/util"
import upload from "./upload"
export default {
    components: { uploadBtn },
    name: "uploadVideo",
    data() {
        return {
            videoFormVisible: false, //上传视频页面是否显示
            carTypeId: 0, //车型id
            formData: {
                videoTitle: "",
                videoUrl: "",
                imageUrl: "",
                expiration_time: null,
                videoClassId: 1,
            },
            rules: {
                videoTitle: [
                    { required: true, message: "请输入标题名称", trigger: "blur" },
                ],
                videoUrl: [
                    { required: true, message: "请上传视频", trigger: "change" },
                ],
                /*
                expiration_time: [
                    { required: true, message: "请选择到期时间", trigger: "change" },
                ],*/
                imageUrl: [
                    { required: true, message: "请上传视频封面", trigger: "blur" },
                ],
            },
            videoClass: [
                { value: 1, label: "产品亮点", }
            ],
            pickerOptions: {
                disabledDate: time => {
                    return (time.getTime() + 8.64e7) < Date.now()
                },
                selectableRange: `00:00:00 - 23:59:59`
            },
            imageList: [], //图片文件列表
            headerHideUpload: false,
            is_done: false,
            disabled: false,
            type: "add",
            videoID: 0,
            row: {}
        };
    },
    watch: {
        "formData.expiration_time"(val, oldVal) {
            this.handleFocus(val)
        }
    },
    methods: {
        handleFocus(val = null) {
            if(!val) val = this.formData.expiration_time
            const date1 = new Date(val)
            const date2 = new Date()
            if(date1.getFullYear() + '-' + date1.getMonth() + '-' + date1.getDate() == 
            date2.getFullYear() + '-' + date2.getMonth() + '-' + date2.getDate()) {
                date2.setMinutes(date2.getMinutes() + 1) // 设置+1分钟
                this.pickerOptions.selectableRange = dateFormatter("hh:mm:ss", date2) + " - 23:59:59"
            } else {
                this.pickerOptions.selectableRange = "00:00:00 - 23:59:59"
            }
        },
        init(carTypeId, row = {}) {
            if (carTypeId == undefined || carTypeId <= 0) {
                this.$message({
                    type: "error",
                    message: "车型不存在！",
                });
                return false;
            }
            this.videoFormVisible = true;
            this.carTypeId = carTypeId;
            if(row.id) {
                this.formData = {
                    videoTitle: row.title,
                    videoUrl: row.video_url,
                    imageUrl: row.image_url,
                    expiration_time: row.expiration_time,
                    videoClassId: parseInt(row.video_class)
                }
                this.imageList = [{url: row.image_url, imageUrl: row.image_url}]
                this.headerHideUpload = true;
                this.disabled = true;
                this.type = "edit";
                this.videoID = row.id,
                this.row = row;
            } else {
                this.formData = {
                    videoTitle: "",
                    videoUrl: "",
                    imageUrl: "",
                    expiration_time: null,
                    videoClassId: 1
                }
            }
        },
        submitForm(formName) {
            // console.log(this.formData);
            //提交配置数据
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    const time = new Date(dateFormatter("YYYY-MM-DD hh:mm", this.formData.expiration_time)).getTime()
                    const time2 = new Date(dateFormatter("YYYY-MM-DD hh:mm")).getTime()
                    if(time <= time2) {
                        this.$message.error("到期时间必须 > 当前时间，精确到分")
                        return false
                    }
                    // 添加
                    if(this.type == "add") {
                        let checked = this.checkFile(this.formData.imageUrl);
                        if (checked) {
                            let data = {
                                brand_id: this.carTypeId,
                                video_url: this.formData.videoUrl,
                                image_url: this.imageList && this.imageList[0] && this.imageList[0].imageUrl,
                                title: this.formData.videoTitle,
                                expiration_time: this.formData.expiration_time,
                                video_class: this.formData.videoClassId
                            }
                            brandModel.saveVideoUrl(data).then(res=>{
					    		if(res.code===1){
					    			this.videoFormVisible = false;
					    			this.$message.success(res.msg);
                                    this.resetForm("uploadVideo");
					    			this.$parent.getList()
					    		}else{
					    			this.$message.error(res.msg)
					    		}
					    	});
                        }
                    } else {
                        let data = {
                            v_id: this.videoID,
                            title: this.formData.videoTitle,
                            image_url: this.imageList && this.imageList[0] && this.imageList[0].imageUrl,
                            expiration_time: this.formData.expiration_time
                        }
                        data.image_url = data.image_url.replace('https://i.mycjj.com/', '')
                        brandModel.updateVideoInfo(data).then(res => {
					    	if(res.code === 1){
					    		this.$message.success("修改成功")
                                //this.row.title = this.formData.videoTitle;
                                //this.row.expiration_time = this.formData.expiration_time;
                                this.videoFormVisible = false;
                                this.resetForm("uploadVideo");
					    		this.$parent.getList()
					    	}else{
					    		this.$message.error(res.msg)
					    	}
					    });
                    }
                } else {
                    console.log("error submit!!");
                    return false;
                }
            });
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
            this.imageList = [];
            this.headerHideUpload = false;
            this.is_done = false;
            this.disabled = false;
            this.type = "add";
            this.videoID = 0;
            this.row = null;
        },
        handleChange(val) {
            this.formData.videoClassId = val;
        },
        handleClose(close) {
            this.$confirm("关闭后数据不会保存！确认关闭？")
                .then((_) => {
                    this.resetForm("uploadVideo");
                    close();
                })
                .catch((_) => { });
        },
        uploadSuccess(val) {
            //视频回调
            this.formData.videoUrl = val;
        },
        //选择图片的回调
        selectFile(file, imageList) {
            this.imageList = imageList;
            this.headerHideUpload = imageList.length >= 1;
            this.formData.imageUrl = file.raw;
        },
        //删除图片的回调
        removeFile(file, imageList) {
            this.imageList = imageList;
            this.headerHideUpload = imageList.length >= 1;
            this.formData.imageUrl = "";
        },
        //上传前检查文件
        checkFile(file) {
            const isJPEG = file.type === "image/jpeg";
            const isJPG = file.type === "image/jpg";
            const isPng = file.type === "image/png";
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isJPEG && !isJPG && !isPng) {
                this.$message.error("上传图片只能是 JPG、PNG 格式!");
                return false;
            }
            if (!isLt2M) {
                this.$message.error("上传图片大小不能超过 2MB!");
                return false;
            }
			return true;
        },
		async handleUploadImg(file) {
            let rep = await upload(
                `/admin/yt_car/index.php?act=yt_car&op=uploadSeriesImage&brand_id=${this.carTypeId}`,
                file
            );
            if (rep.code === 200) {
                this.imageList.map((image) => {
                    if (image.uid == file.file.uid) {
                        image.imageUrl = rep.data.filename;
                    }
                });
            }
        },
    },
    created() { },
    mounted() { },
};
</script>

<style lang="scss">
.el-dialog {
    .el-dialog__header {
        padding-bottom: 5px;
    }
    .el-dialog__body {
        padding: 10px 10px;
    }
    .el-divider--horizontal {
        margin-top: 0px;
    }
    .el-form {
        padding-right: 10px;
    }
    .btnSave {
        float: right;
        margin-right: 5px;
        width: 88px;
    }
    .local-hide .el-upload--picture-card {
        display: none;
    }
    .header-img .el-upload-list--picture-card .el-upload-list__item {
        width: 120px;
    }
    .header-img .el-upload-list--picture-card .el-upload-list__item {
        height: 162px;
        line-height: 92px;
    }
    .el-upload__tip {
        margin-top: 0px;
    }
    .el-upload-list__item-status-label {
        display: none!important;
    }
}
</style>